package com.zwps.biz.domain.service.impl;

import java.io.InputStream;
import org.springframework.stereotype.Service;

import com.zwps.biz.domain.enums.FileStoreTypeEnum;
import com.zwps.biz.domain.model.pojo.FileUploadResultPOJO;
import com.zwps.biz.domain.service.MinioFileStoreService;
import com.zwps.common.core.exception.UserActionException;
import com.zwps.common.minio.config.MinioConfigProperties;
import com.zwps.common.minio.service.MinioService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class MinioFileStoreServiceImpl implements MinioFileStoreService {

    private MinioService minioService;

    private MinioConfigProperties minioConfig;

    @Override
    public FileUploadResultPOJO upload(InputStream stream, String path, String fileName) {
        try {
            String filePath = minioService.upload(stream, path, fileName);
            FileUploadResultPOJO pojo = new FileUploadResultPOJO();
            pojo.setFilePath(filePath);
            pojo.setFileUrl(minioConfig.getExternalUrl() + "/" + filePath);
            pojo.setFileInternalUrl(minioConfig.getInternalUrl() + "/" + filePath);
            pojo.setStoreType(FileStoreTypeEnum.MINIO);
            return pojo;
        } catch (Exception e) {
            log.error("upload file[{}] to Minio error: {}", fileName, e);
            throw new UserActionException("上传文件失败");
        }
    }

    @Override
    public void delete(String filePath) {
        try {
            String bucketName = minioConfig.getBucketName();
            int index = filePath.indexOf(bucketName);
            String objectName = filePath;
            if (index > -1) {
                objectName = filePath.substring(index + bucketName.length());
            }
            minioService.removeObject(bucketName, objectName);
        } catch (Exception e) {
            log.error("delete file path[{}] to Minio error: {}", filePath, e);
            throw new UserActionException("删除文件失败");
        }
    }

}
